#include <iostream>

using namespace std;

void minKofN(int a[], int n, int b[], int k)
{
	cout<<__func__<<endl;
	cout<<"n="<<n<<" k="<<k<<endl;
	int num = 0;

	for(int i = 0; i < n; i++)
	{
		cout<<i<<endl;
		if(num < k)
		{
			b[num] = a[i];
			for(int j = num; j > 0; j--)
			{
				if(b[j] > b[(j - 1) / 2])
				{
					int temp = b[j];
					b[j] = b[(j - 1) / 2];
					b[(j - 1) / 2] = temp;
				}
			}
			num++;
		}
		else
		{
			if(a[i] >= b[0])
				continue;
			else
			{
				b[0] = a[i];
				int m = 0;
				while(m < k / 2)
				{
					if(b[2 * (m + 1) - 1] > b[2 * (m + 1)] && b[2 * (m + 1) - 1] > b[m])
					{
						int temp = b[2 * (m + 1) - 1];
						b[2 * (m + 1) - 1] = b[m];
						b[m] = temp;
						m = 2 * (m + 1) - 1;
					}
					else if(b[2 * (m + 1)] > b[2 * (m + 1) - 1] && b[2 * (m + 1)] > b[m])
					{
						int temp = b[2 * (m + 1)];
						b[2 * (m + 1)] = b[m];
						b[m] =temp;
						m = 2 * (m + 1);
					}
					else
						break;
				}
			}
		}
	}
}

int main()
{
	int a[8] = {3, 43, 54 ,34, 22 , 87, 2, 11};
	int b[4];
	minKofN(a, 8, b, 4);
	for(int i = 0; i < 4; i++)
	{
		cout<<b[i]<<" ";
	}
	cout<<endl;
}
